package com.eroad.product.tools;

import xf.tools.CustomToast;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.view.KeyEvent;
import android.widget.Toast;

/** <b>back监听事件</b> */
public class DoubleClickExitApp {

	private Activity mcontext;
	/** 是否是再次点击back键 */
	private boolean isOnKeyBack;
	private Handler mHandler;
	/** 退出提示Toast */
	private Toast mExitToast;

	public DoubleClickExitApp(Activity context) {
		this.mcontext = context;
		this.mHandler = new Handler(Looper.getMainLooper());
	}

	/** 所在Activity中的点击返回事件处理 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode != KeyEvent.KEYCODE_BACK) {// 如果不是点击的返回键，则返回false
			return false;
		}
		if (isOnKeyBack) {// 第二次点击,做关闭和销毁一系列释放操作
			mHandler.removeCallbacks(onBackExitRunnable);// 线程清理
			if (mExitToast != null) {
				mExitToast.cancel();
			}
			/** 直接退出 */
			// mcontext.finish();
			isOnKeyBack = false;
			HOME(mcontext);// 模拟home键,直接到桌面,不关闭app
			CustomToast.disToast();
			return true;
		} else {// 第一次点击,做提示
			isOnKeyBack = true;
			CustomToast.showToast(mcontext, "再次点击回到桌面", 1500);
			mHandler.postDelayed(onBackExitRunnable, 2000);
			return true;
		}
	}

	/** 标识修改taost,是否第一次或第二次没在规定时间触发,则把标示重置 */
	private Runnable onBackExitRunnable = new Runnable() {
		@Override
		public void run() {
			isOnKeyBack = false;
			if (mExitToast != null) {
				mExitToast.cancel();
			}
		}
	};

	/** Home键效果，回到桌面 */
	public void HOME(Context context) {
		Intent intent = new Intent();
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_HOME);
		context.startActivity(intent);
	}
}
